package com.lwl.concurrency.executor;

import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by liwenlong on 2018/1/11 12:43
 */
public class FutureTaskTest {

    public static class ExecutableCallable implements Callable<String> {

        private String name;

        public ExecutableCallable(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String call() throws Exception {
            int i = new Random().nextInt(10);
            TimeUnit.SECONDS.sleep(i);
            return "任务执行完成" + name;
        }
    }

    public static class ResultTask extends FutureTask<String> {

        private String name;

        public ResultTask(Callable<String> callable) {
            super(callable);
            this.name = ((ExecutableCallable) callable).getName();
        }

        @Override
        protected void done() {
            if (isCancelled()) {
                System.out.println("has been cancel " + name);
            } else {
                System.out.println("has finished " + name);
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ResultTask[] resultTasks = new ResultTask[5];
        Future[] futures = new Future[5];
        for (int i = 0; i < resultTasks.length; i++) {
            ExecutableCallable task = new ExecutableCallable("Task-" + i);
            resultTasks[i] = new ResultTask(task);
            Future<?> submit = executorService.submit(resultTasks[i]);
            futures[i] = submit;
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < resultTasks.length; i++) {
            System.out.println(futures[i] == resultTasks[i]);
            resultTasks[i].cancel(true);
        }
        for (int i = 0; i < resultTasks.length; i++) {
            try {
                if (!resultTasks[i].isCancelled()) {
                    System.out.println(resultTasks[i].get());
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        executorService.shutdown();
    }


}
